<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item>
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增用户组</el-button>
        <el-button type="danger" :icon="Delete" :disabled="multiple" @click="handleDelete">
          {{ $t('system.globalParam.Delete') }}
        </el-button>
      </el-form-item>
      <el-form-item prop="groupName">
        <el-input v-model="queryParams.groupName" :placeholder="$t('system.group.groupUser')" clearable
                  @keyup.enter="refresh"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="refresh">{{ $t('system.globalParam.Search') }}</el-button>
        <el-button :icon="Refresh" @click="resetQuery">{{ $t('system.globalParam.Reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据表格 -->
    <es-table :dataGetter="handleQuery" class="es-table" header-cell-class-name="app-table-head table-head-center"
              ref="dataTableRef"
              @selection-change="handleSelectionChange"
              @row-click="handleRowClick" highlight-current-row border>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column :label="$t('system.group.groupUser')" align="center" prop="groupName"/>
      <el-table-column :label="$t('system.group.Sort')" align="center" prop="sort"/>
      <el-table-column :label="$t('system.group.Description')" align="center" prop="remark"/>
      <el-table-column :label="$t('source.DataSourceConfiguration.createTime')" align="center" prop="createOn"
                       width="180"/>
      <el-table-column :label="$t('source.DataSourceConfiguration.Operation')" align="center" width="200">
        <template #default="scope">
          <!--            <el-button type="success" :icon="Operation" circle plain @click.stop="openRoleResourceDialog(scope.row)"/>-->
          <!--          <el-button type="primary" :icon="Edit" circle plain @click.stop="handleUpdate(scope.row)"/>-->
          <Edit class="operation-icon" color="#409eff" @click.stop="handleUpdate(scope.row)"/>
          <!--          <el-button type="danger" :icon="Delete" circle plain @click.stop="handleDelete(scope.row)"/>-->
          <Delete class="operation-icon" color="#409eff" @click.stop="handleDelete(scope.row)"/>
        </template>
      </el-table-column>
    </es-table>
    <!-- 表单弹窗 -->
    <el-dialog :close-on-click-modal="false" :title="dialog.title" v-model="dialog.visible" width="500px"
               destroy-on-close>
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="auto">
        <el-form-item :label="$t('system.group.groupUser')" prop="roleCode">
          <el-input v-model="formData.groupName" :placeholder="$t('system.group.enterPlease')"/>
        </el-form-item>
        <el-form-item :label="$t('system.group.Sort')" prop="roleDesc">
          <el-input v-model="formData.sort" :placeholder="$t('system.group.sortPlease')"/>
        </el-form-item>
        <el-form-item :label="$t('system.group.Description')" prop="roleDesc">
          <el-input v-model="formData.remark" :placeholder="$t('system.group.descriptionPlease')"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">{{ $t('system.globalParam.Cancel') }}</el-button>
          <el-button type="primary" @click="submitFormData">{{ $t('system.globalParam.Confirm') }}</el-button>

        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
export default {
  name: "group"
}
</script>
<script setup lang="ts">
import {reactive, ref, onMounted, toRefs, unref} from "vue";
import {Search, Plus, Edit, View, Refresh, Delete,} from "@element-plus/icons-vue";
import {ElForm, ElMessage, ElMessageBox, ElPopover} from "element-plus/es";
import EsTable from "@/components/es-table/index.vue";

//API
import {addGroup, deleteGroups, listGroupPages, updateGroup} from "@/services/system/group";
import {GroupFormData, GroupItem, GroupQueryParam} from "@/types/system/group";
import {getRoleFormDetail} from "@/services/system/role";
import {listResources} from "@/services/system/menu";
import {deleteUsers} from "@/services/system/user";
import {useI18n} from 'vue-i18n'

const {t} = useI18n()
const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const dataTableRef = ref();

const state = reactive({
  loading: true,
  // 选中ID数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  queryParams: {
    pageNum: 1,
    pageSize: 8,
  } as GroupQueryParam,
  groupList: [] as GroupItem[],
  total: 0,
  dialog: {
    title: '',
    visible: false,
  },
  formData: {} as GroupFormData,
  rules: {
    groupName: [{required: true, message: t('system.group.enterPlease'), trigger: 'blur'}],
    sort: [{required: true, message: t('system.group.sortPlease'), trigger: 'blur'}],
  },
});
const {
  loading,
  multiple,
  queryParams,
  groupList,
  total,
  dialog,
  formData,
  rules,
  resourceDialogVisible,
  checkedRole,
  resourceOptions
} = toRefs(state);


function handleAdd() {
  state.dialog = {
    title: t('system.group.groupAdd'),
    visible: true,
  };
}

function handleUpdate(row: any) {
  state.dialog = {
    title: t('system.group.groupModify'),
    visible: true,
  };
  state.formData = JSON.parse(JSON.stringify(row));
}

function submitFormData() {
  loading.value = true;
  //验证
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      if (state.formData.id) {
        updateGroup(state.formData.id as any, state.formData).then(() => {
          ElMessage.success(t('system.group.modifyingSucceeded'));
          cancel();
          refresh();
        });
      } else {
        addGroup(state.formData).then(() => {
          cancel();
          formData.value = {};
          ElMessage.success(t('system.group.addingSucceeded'));
          refresh();
        });
      }
    }
  });
}

/**
 * 删除用户
 */
function handleDelete(row: { [key: string]: any }) {
  const groupIds = row.id || state.ids.join(',');
  ElMessageBox.confirm(t('system.group.dataitemDelete'), t('system.role.Warning'), {
    confirmButtonText: t('system.globalParam.Confirm'),
    cancelButtonText: t('system.globalParam.Cancel'),
    type: 'warning',
  }).then(function () {
    deleteGroups(groupIds).then(() => {
      ElMessage.success(t('system.tenant.deleteS'));
      refresh();
    });
  }).catch(() => ElMessage.info(t('system.tenant.Undeleted')));
}

/**
 * 表格行选中事件
 */
function handleSelectionChange(selection: any) {
  state.ids = selection.map((item: any) => item.id);
  state.single = selection.length !== 1;
  state.multiple = !selection.length;
}

/**
 * 取消
 */
function cancel() {
  loading.value = false;
  dialog.value.visible = false;
  formData.value.id = undefined;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
}

/**
 * 查询
 */
// function handleQuery() {
//   state.loading = true;
//   listGroupPages(state.queryParams).then(({data}) => {
//     state.groupList = data.records;
//     state.total = data.total;
//     state.loading = false;
//   });
// }
function handleQuery(page: any) {
  if (page) {
    state.queryParams.pageNum = page.page;
    state.queryParams.pageSize = page.limit;
  }
  return listGroupPages(state.queryParams).then(({data}) => {
    return data
  });
}

const refresh = () => {
  unref(dataTableRef).reload()
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  unref(dataTableRef).reload()
}

</script>

<style scoped>

</style>
